
//
//  WHOAuthViewController.swift
//  8.31-WH微博
//
//  Created by 吴涵 on 15/9/2.
//  Copyright © 2015年 wuhan. All rights reserved.
//

import UIKit
import SVProgressHUD
class WHOAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        super.loadView()
         view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
 
        view.backgroundColor = UIColor.whiteColor()
        
        webView.delegate = self
        
        webView.loadRequest(NSURLRequest(URL: WHWebTools.sharedTools.url))
        
        title = "三方登陆"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    func close(){
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    func autoFill(){
        let js = "document.getElementById('userId').value = '780074526@qq.com';"+"document.getElementById('passwd').value = 'gege186043';"
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(WHWebTools.sharedTools.redirectUrl){
            return true
        }
        if let query = request.URL!.query where query.hasPrefix("code="){
            let code = query.substringFromIndex("code=".endIndex)
            printLog("请求🐴++++\(code)")
            // 加载数据，转成字典
           UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
            printLog(error)
            }, completed: { () -> Void in
                
                printLog("登录完成111111")
                SVProgressHUD.dismiss()
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(WHSwithRootControllerNotification, object: "12321")
                })
           })
//
        
        }else{
            print("取消")
//        self.close()
        }
        return false
    }
   
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
